#!usr/bin/env python
#coding=utf8

from tuangou.models.tuan_models import Item, ItemImage, Supplier, ItemLinkSupplier, HotItem
from tuangou.common_logic import commutil

def get_hotitem_list():
    hots = HotItem.objects.all()
    for hot in hots:
        try:
            item = hot.item
            hot.item.homeimage = item.itemimage_set.filter(imagetype='home')[0]
        except:
            hot.item.homeimage = ItemImage(thumburl='', imagetype='home', originalurl='')
    return hots    

def get_hotitem_by_id(id):
    try:
        hot = HotItem.objects.get(id=id)
        item = hot.item
        hot.item.homeimage = item.itemimage_set.filter(imagetype='home')[0]
    except:
        hot = None
        
    return hot

def save_hotitem(id, index):
    h = HotItem.objects.get(id=id)
    if h:
        h.index = index
        h.save()

def add_hotitem(index, item_id):
    h = HotItem()
    h.index = index
    h.item_id = item_id
    h.save()

def delete_hotitem(id):
    item = HotItem.objects.get(id=id)
    item.delete()

def search_item_list(keyword):
    items = Item.objects.filter(title__contains=keyword)[0 : 30]
    for item in items:
        try:
            item.homeimage = item.itemimage_set.filter(imagetype='home')[0]
        except:
            item.homeimage = ItemImage(thumburl='', imagetype='home', originalurl='')
    return items

def get_hotitem_to_index():
    hots = HotItem.objects.all()[0 : 10]
    for hot in hots:
        try:
            item = hot.item
            item.price = commutil.decimalFormat(item.price)
            item.tuanprice = commutil.decimalFormat(item.tuanprice)
            hot.item.homeimage = item.itemimage_set.filter(imagetype='home')[0]
        except:
            hot.item.homeimage = ItemImage(thumburl='', imagetype='home', originalurl='')
    return hots